package net.maku.generator.controller;

import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import net.maku.generator.common.exception.ServerException;
import net.maku.generator.common.utils.Result;
import net.maku.generator.service.GeneratorService;
import net.maku.generator.utils.Merge;
import net.maku.generator.vo.PreviewVO;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.io.FileUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 代码生成
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("maku-generator/gen/generator")
@AllArgsConstructor
public class GeneratorController {
    private final GeneratorService generatorService;

    /**
     * 生成代码（zip压缩包）
     */
    @GetMapping("download")
    public void download(String tableIds, HttpServletResponse response) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);


        List<String> docPath=new ArrayList<>();
        // 生成代码
        for (String tableId : tableIds.split(",")) {
            generatorService.downloadCode(Long.parseLong(tableId), zip);
            try {
                // 假设有一个docx文件的路径
                File docxFile = generatorService.getDocFile(Long.valueOf(tableId));
                // 添加docx文件到zip
                //zip.putNextEntry(new ZipEntry(docxFile.getName())); // 使用文件名作为条目名称
                docPath.add(docxFile.getAbsolutePath());//获取文件绝对路径
                //IoUtil.write(zip, false, FileUtil.getInputStream(docxFile).readAllBytes()); // 将docx文件内容写入ZIP
                //zip.flush();
                //zip.closeEntry();
            } catch (Exception e) {
                System.out.println("v--------------------------docgenerror");
            }
        }
        String mergeDoc= Merge.wordMerge(docPath);
        try {
            // 假设有一个docx文件的路径
            File docxFile = new File(mergeDoc);
            // 添加docx文件到zip
            zip.putNextEntry(new ZipEntry(docxFile.getName())); // 使用文件名作为条目名称
            IoUtil.write(zip, false, FileUtil.getInputStream(docxFile).readAllBytes()); // 将docx文件内容写入ZIP
            zip.flush();
            zip.closeEntry();
        } catch (Exception e) {
            System.out.println("v--------------------------docgenerror");
        }
        IoUtil.close(zip);

        // zip压缩包数据
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"maku.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }

    /**
     * 生成代码（自定义目录）
     */
    @ResponseBody
    @PostMapping("code")
    public Result<String> code(@RequestBody Long[] tableIds) throws Exception {
        // 生成代码
        for (Long tableId : tableIds) {
            generatorService.generatorCode(tableId);
        }

        return Result.ok();
    }
    /**
     * 预览代码
     */
    @GetMapping("/preview")
    public Result<List<PreviewVO>> preview(@RequestParam Long tableId) throws Exception {
        List<PreviewVO> results = generatorService.preview(tableId);
        return Result.ok(results);
    }
}